import { listMyChartVoByPageUsingPost } from '@/services/xiBI/chartController';
import { Avatar, List, message, Typography, Row, Col, Card, Input } from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';
import { useModel } from '@@/exports';

const { Title, Paragraph } = Typography;
const { Search } = Input;



const MyChartPage: React.FC = () => {
  const initSearchParams = {
    pageSize: 12,
    current: 1,
    sortField: 'createTime',
    sortOrder: 'desc'
  };

  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });
  const [chartList, setChartList] = useState<API.Chart[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};

  const loadData = async () => {
    setLoading(true);
    try {
      const res = await listMyChartVoByPageUsingPost(searchParams);
      if (res.data) {
        // 将新数据添加到列表前面
        setChartList((prevList) => {
          const newRecords = res.data.records ?? [];
          return [...newRecords, ...prevList.filter(item => !newRecords.some(record => record.id === item.id))];
        });
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取我的图表失败。');
      }
    } catch (e: any) {
      message.error('获取我的图表失败,' + e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [searchParams]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchParams({
      ...initSearchParams,
      name: value, // 将搜索关键词添加到 searchParams
    });
  };

  return (
    <div className="my-chart-page" style={{ padding: '24px' }}>
      <Row gutter={[24, 24]}>
        <Col span={24}>
          <Card
            title={
              <Row justify="space-between" align="middle">
                <Title level={4} style={{ marginBottom: 0 }}>我的图表</Title>
                <Search
                  placeholder="输入图表标题搜索"
                  allowClear
                  enterButton="搜索"
                  size="large"
                  onSearch={handleSearch}
                  style={{ width: '400px' }}
                />
              </Row>
            }
            bordered={false}
            style={{ boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)', borderRadius: '8px' }}
          >
            <List
              itemLayout="vertical"
              size="large"
              loading={loading}
              pagination={{
                onChange: (page) => {
                  setSearchParams({ ...searchParams, current: page });
                },
                pageSize: initSearchParams.pageSize,
                total,
                showSizeChanger: false,
              }}
              dataSource={chartList}
              renderItem={(item, index) => (
                <Row gutter={24} key={item.id}>
                  <Col span={12}>
                    <List.Item
                      style={{
                        padding: '24px',
                        marginBottom: '16px',
                        borderRadius: '8px',
                        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                        backgroundColor: '#fff',
                        borderBottom: '1px solid #f0f0f0', // 添加分割线
                      }}
                    >
                      <List.Item.Meta
                        avatar={
                          <Avatar
                            src={currentUser?.userAvatar || 'https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png'}
                            size={64}
                            style={{ borderRadius: '50%' }}
                          />
                        }
                        title={<Title level={5} style={{ marginBottom: '8px' }}>{item.name}</Title>}
                        description={
                          <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                            图表类型：{item.chartType ?? '未知'}
                          </Paragraph>
                        }
                      />
                      <Paragraph style={{ marginTop: '16px', fontWeight: 'bold', color: '#333' }}>
                        分析目标：{item.goal}
                      </Paragraph>
                      <div style={{ marginTop: '24px' }}>
                        {item.status === 'running' ? (
                          <div style={{ textAlign: 'center', fontSize: '18px', color: '#1890ff' }}>
                            正在生成中...
                          </div>
                        ) : item.status === 'wait' ? (
                          <div style={{ textAlign: 'center', fontSize: '18px', color: '#faad14' }}>
                            等待生成
                          </div>
                        ) : (
                          <ReactECharts
                            option={item.genChart ? JSON.parse(item.genChart) : {}}
                            style={{ width: '100%', height: '400px' }}
                          />
                        )}
                      </div>
                    </List.Item>
                  </Col>
                  {chartList[index + 1] && (
                    <Col span={12}>
                      <List.Item
                        style={{
                          padding: '24px',
                          marginBottom: '16px',
                          borderRadius: '8px',
                          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                          backgroundColor: '#fff',
                          borderBottom: '1px solid #f0f0f0', // 添加分割线
                        }}
                      >
                        <List.Item.Meta
                          avatar={
                            <Avatar
                              src={currentUser?.userAvatar || 'https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png'}
                              size={64}
                              style={{ borderRadius: '50%' }}
                            />
                          }
                          title={<Title level={5} style={{ marginBottom: '8px' }}>{chartList[index + 1].name}</Title>}
                          description={
                            <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                              图表类型：{chartList[index + 1].chartType ?? '未知'}
                            </Paragraph>
                          }
                        />
                        <Paragraph style={{ marginTop: '16px', fontWeight: 'bold', color: '#333' }}>
                          分析目标：{chartList[index + 1].goal}
                        </Paragraph>
                        <div style={{ marginTop: '24px' }}>
                          {chartList[index + 1].status === 'running' ? (
                            <div style={{ textAlign: 'center', fontSize: '18px', color: '#1890ff' }}>
                              正在生成中...
                            </div>
                          ) : chartList[index + 1].status === 'wait' ? (
                            <div style={{ textAlign: 'center', fontSize: '18px', color: '#faad14' }}>
                              等待生成
                            </div>
                          ) : (
                            <ReactECharts
                              option={chartList[index + 1].genChart ? JSON.parse(chartList[index + 1].genChart) : {}}
                              style={{ width: '100%', height: '400px' }}
                            />
                          )}
                        </div>
                      </List.Item>
                    </Col>
                  )}
                </Row>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default MyChartPage;
